﻿using System;
using System.Data;
using System.Globalization;
using System.IO;
using Business;

namespace Presentation.Posts
{
    public partial class NewPost : System.Web.UI.Page
    {
        private CategoryBsl _category;
        private PostBll _postBll;
        protected void Page_Load(object sender, EventArgs e)
        {
            _category = new CategoryBsl();
            if(!IsPostBack)
            {
                DataTable dataTable = _category.ViewAllCategories();
                DropDownCategory.DataSource = dataTable.DefaultView;
                DropDownCategory.DataBind();
                ;
            }
        }

        protected void Publish_Click(object sender, EventArgs e)
        {
            IFormatProvider iFormatProvider = new CultureInfo("en-gb");
            _postBll = new PostBll();
            if(IsAccept.Checked == true)
            {
                string title = PostTitle.Text;
                int cateId = Convert.ToInt32(DropDownCategory.SelectedValue, iFormatProvider);
                string shortDescription = PostSummary.Text;
                int userId = 1;
                string content = TextContent.Text;
                DateTime datePost = DateTime.Now;
                string imageLink = "";
                int status = 1;
                if (AvatarImage.HasFile)
                {
                    try
                    {
                        string fileName = Path.GetFileName(AvatarImage.FileName);
                        AvatarImage.SaveAs(Server.MapPath("~/Resources/images") + fileName);
                        imageLink = ("/Resources/images" + fileName);
                    }
                    catch (Exception exception)
                    {
                        RequiredFieldValidator2.ErrorMessage = exception.Message;
                    }
                }
                _postBll.CreatePost(title, shortDescription, content, imageLink, datePost, status, userId, cateId);
                Response.Redirect("Default.aspx");
            }
        }
    }
}
